package org.csu.question.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.csu.question.entity.dto.KnowledgePointStats;
import org.csu.question.entity.po.AnswerRecord;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface AnswerRecordMapper extends BaseMapper<AnswerRecord> {

    /**
     * 查询用户最近的答题记录
     */
    @Select("SELECT * FROM answer_records WHERE user_id = #{userId} " +
            "ORDER BY answered_at DESC LIMIT #{limit}")
    List<AnswerRecord> selectRecentRecords(@Param("userId") Long userId, @Param("limit") Integer limit);

    /**
     * 查询用户在指定时间范围内的答题记录
     */
    @Select("SELECT * FROM answer_records WHERE user_id = #{userId} " +
            "AND answered_at >= #{startTime} ORDER BY answered_at DESC")
    List<AnswerRecord> selectRecordsByTimeRange(@Param("userId") Long userId,
                                                @Param("startTime") LocalDateTime startTime);

    /**
     * 查询用户各知识点的答题统计
     */
    @Select("SELECT " +
            "kp.id as knowledge_point_id, " +
            "kp.name as knowledge_point_name, " +
            "kp.tag as tag, " +
            "COUNT(ar.id) as total_count, " +
            "SUM(CASE WHEN ar.is_correct = 1 THEN 1 ELSE 0 END) as correct_count, " +
            "AVG(CASE WHEN ar.is_correct = 1 THEN 1.0 ELSE 0.0 END) as correct_rate " +
            "FROM answer_records ar " +
            "LEFT JOIN questions q ON ar.question_id = q.id " +
            "LEFT JOIN knowledge_points kp ON q.knowledge_point_id = kp.id " +
            "WHERE ar.user_id = #{userId} " +
            "GROUP BY kp.id, kp.name, kp.tag")
    List<KnowledgePointStats> selectUserKnowledgePointStats(@Param("userId") Long userId);

    /**
     * 查询用户指定知识点的最近答题记录
     */
    @Select("SELECT ar.* FROM answer_records ar " +
            "LEFT JOIN questions q ON ar.question_id = q.id " +
            "WHERE ar.user_id = #{userId} AND q.knowledge_point_id = #{knowledgePointId} " +
            "ORDER BY ar.answered_at DESC LIMIT #{limit}")
    List<AnswerRecord> selectRecentRecordsByKnowledgePoint(
            @Param("userId") Long userId,
            @Param("knowledgePointId") Long knowledgePointId,
            @Param("limit") Integer limit);
}
